package com.lyz.myself.config.utils.oss;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.model.*;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by lightClouds917
 * Date 2018/2/7
 * Description:aliyunOSSUtil
 */
public class AliyunOSSUtil {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
    /**
     * 获取阿里云OSS客户端对象
     *
     * @return ossClient
     */
    public static OSSClient getOSSClient() {
        // 创建ClientConfiguration实例，按照您的需要修改默认参数。
        return new OSSClient(ConstantProperties.OSS_END_POINT, ConstantProperties.OSS_ACCESS_KEY_ID, ConstantProperties.OSS_ACCESS_KEY_SECRET);
    }
    /**
     * 创建存储空间
     *
     * @param ossClient
     *            OSS连接
     * @param bucketName
     *            存储空间
     * @return
     */
    public static String createBucketName(OSSClient ossClient, String bucketName) {
        // 存储空间
        final String bucketNames = bucketName;
        if (!ossClient.doesBucketExist(bucketName)) {
            // 创建存储空间
            Bucket bucket = ossClient.createBucket(bucketName);
            logger.info("创建存储空间成功");
            return bucket.getName();
        }
        return bucketNames;
    }

    /**
     * 删除存储空间buckName
     *
     * @param ossClient
     *            oss对象
     * @param bucketName
     *            存储空间
     */
    public static void deleteBucket(OSSClient ossClient, String bucketName) {
        ossClient.deleteBucket(bucketName);
        logger.info("删除" + bucketName + "Bucket成功");
    }

    /**
     * 创建模拟文件夹
     *
     * @param ossClient
     *            oss连接
     * @param bucketName
     *            存储空间
     * @param folder
     *            模拟文件夹名如"qj_nanjing/"
     * @return 文件夹名
     */
    public static String createFolder(OSSClient ossClient, String bucketName, String folder) {
        // 文件夹名
        final String keySuffixWithSlash = folder;
        // 判断文件夹是否存在，不存在则创建
        if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
            // 创建文件夹
            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
            logger.info("创建文件夹成功");
            // 得到文件夹名
            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
            String fileDir = object.getKey();
            return fileDir;
        }
        return keySuffixWithSlash;
    }

    /**
     * 根据key删除OSS服务器上的文件

     * @param key Bucket下的文件的路径名+文件名 如："upload/cake.jpg"
     */
    public static List<String> deleteFile(String key) {
        OSSClient ossClient = AliyunOSSUtil.getOSSClient();
    // 删除文件。
        List<String> keys = new ArrayList<String>();
     /*   keys.add(key);
//        keys.add("key1");
//        keys.add("key2");

        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(ConstantProperties.OSS_BUCKET_NAME).withKeys(keys));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();

        // 关闭OSSClient。
        ossClient.shutdown();*/

// 删除文件。
        ossClient.deleteObject(ConstantProperties.OSS_BUCKET_NAME, key);

// 关闭OSSClient。
        ossClient.shutdown();
        List<String> deletedObjects = new ArrayList<>();
//        logger.info("删除" + ConstantProperties.OSS_BUCKET_NAME + "下的文件" + ConstantProperties.OSS_FILE_HOST +"/"+ key + "成功");
        logger.info("删除" + ConstantProperties.OSS_BUCKET_NAME + "下的文件    /"+ key + "成功");
        return deletedObjects;
    }
    /**
     * 上传图片至OSS 文件流
     * @param file
     *  存储空间
     * @return String 返回的唯一MD5数字签名
     */
    public static String[] uploadObject2OSS( File file) {
        OSSClient ossClient = AliyunOSSUtil.getOSSClient();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String FORMAT = format.format(new Date());
        String resultStr = null;
        String[] fo = new String[] { "", "" };
        try {
            // 以输入流的形式上传文件
            String folder = "";
            folder = ConstantProperties.OSS_FILE_HOST +"/"+ FORMAT + "/";
            InputStream is = new FileInputStream(file);
            // 文件名
            String fileName = file.getName();
            fileName = UUID.randomUUID().toString().replace("-","")+"-"+file.getName();
            logger.info("上传到路径" + folder + fileName);
            // 文件大小
            Long fileSize = file.length();
            // 创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            // 上传的文件的长度
            metadata.setContentLength(is.available());
            // 指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            // 指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            // 指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            // 如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(fileName));
            // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            // 上传文件 (上传文件流的形式)
            PutObjectResult putResult = ossClient.putObject(ConstantProperties.OSS_BUCKET_NAME, folder + fileName, is, metadata);
            // 解析结果
            resultStr = putResult.getETag();
            fo[1] = folder + fileName;
            fo[0] = resultStr;

            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }
        return fo;
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName
     *            文件名
     * @return 文件的contentType
     */
    public static String getContentType(String fileName) {
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".mp4".equalsIgnoreCase(fileExtension)) {
            return "video/mp4";
        }
        // 默认返回类型
        return "image/jpeg";
    }
    /**
     * 获得url链接
     *
     * @return
     */
    public static String getUrl(String bucketName, String fileName) {
        OSSClient ossClient = AliyunOSSUtil.getOSSClient();
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
        if (url != null) {
            return url.toString();
        }
        return "获网址路径出错";
    }
    public String uploadvideo(String url){
        String[] urllist=AliyunOSSUtil.uploadObject2OSS(new File(url));
        String c=urllist[1];
        return c;
    }
    // 测试
    public static void main(String[] args) throws Exception {
        AliyunOSSUtil t = new AliyunOSSUtil();
        String url = t.uploadvideo("g:\\余杰的avi小视频.mp4");
        System.out.println(url);
        /*// 初始化OSSClient
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        // 上传文件
        String files = "D:\\1.jpg";
        String[] file = files.split(",");
        String user_id = "3";

         * for (String filename : file) { //
         * System.out.println("filename:"+filename); File filess = new
         * File(filename); String[] s =
         * AliyunOSSClientUtil.uploadObject2OSS(ossClient, filess, BACKET_NAME,
         * user_id); logger.info("上传后的文件MD5数字唯一签名:" + s[0]); logger.info("文件路径:"
         * + s[1]); String url = AliyunOSSClientUtil.getUrl(ossClient,
         * BACKET_NAME, s[1]); logger.info("访问网址路径:" + url); //
         * 上传后的文件MD5数字唯一签名:40F4131427068E08451D37F02021473A }


        byte[] b1 = AliyunOSSClientUtil.image2byte("g:\\余杰AVI.png");

         * String str =
         * "";
         * BASE64Decoder decoder = new BASE64Decoder(); byte[] b =
         * decoder.decodeBuffer(str);
         *
         * System.out.println(b.length);


//        String path = AliyunOSSClientUtil.uploadByteVideoOSS(ossClient, b1, BACKET_NAME, user_id);
        String path = AliyunOSSClientUtil.uploadByteOSS(ossClient, b1, BACKET_NAME, user_id);
//        String path = AliyunOSSClientUtil.uploadObjectOSS(ossClient, b1, BACKET_NAME, user_id);
        System.out.println(b1.length + "," + b1.toString());
        logger.info("文件路径:" + path);
        String url = AliyunOSSClientUtil.getUrl(ossClient, BACKET_NAME, path);
        logger.info("访问网址路径:" + url);*/
    }
}
